package com.myacg.core.entity.img;


import com.myacg.core.task.KeepTask;
import com.myacg.core.task.KeepTaskManager;


/**
 * 动画播放器 ， 实际是通过维护 图片数组的指针来对播放进行控制
 * @author Administrator
 *
 */
public abstract class AnimationPlayer {
	private String[] frames;//帧序列
	private int nowPos;  //当前位置
	private int sleepTime;//间隔
	private boolean isloop; //是否循环
	private int status;//状态  0 停止  1运行 2暂停
	private KeepTask  keepTask;//任务类
	
	protected AnimationPlayer(){}
	protected   AnimationPlayer(String[] frames,int sleepTime,boolean isloop){
		this.frames=frames;
		this.sleepTime=sleepTime;
		this.isloop=isloop;
		nowPos=0;
		status=0;
	}
	
	 
	
	/**
	 * 被停止时触发的操作
	 */
	public abstract void overExec();
	 
	
	/**
	 * 播放一帧
	 */
	private  void playOneStep(){
		if(status==1){
			if(frames!=null){
				if(nowPos<frames.length-1){
					nowPos++;
					//如果播放完一轮
					if(nowPos==frames.length-1){
						if(isloop){ //继续
							nowPos=0;
						}else{      //停止
							this.stop(); //通知解除任务
						}
					}
				} 
			}
		}
		 
	}
	
	/**
	 * 暂停
	 */
	public void pause(){
		this.status=2;
	}
	/**
	 * 启动任务 并启动定时器任务进行 固定间隔的周期循环
	 */
	public void  start(){
		this.status=1;
		if(keepTask==null){
			keepTask=new KeepTask(sleepTime) {
				@Override
				public void secondExecute() {
					//每个间隔执行一次
					playOneStep();
				}
				@Override
				public void overExecute() {
					System.out.println("AnimationPlayer is stop!");
				}
			};
			//加入任务
			KeepTaskManager.getInstance().addTask(keepTask);
		}
	}
	
	/**
	 * 主动触发一移除任务
	 */
	public void  stop(){
		if(keepTask!=null){
			keepTask.over(); //通知KeepTaskManager 移除自己
			keepTask=null;   //销毁task
		}
		this.status=0;
		overExec();
	}
	
	/**
	 * 重启， 从首部开始播放
	 */
	public void reStart(){
		nowPos=0; //重置图片指针
		start();
	}
	
	/**
	 * gets and sets
	 * @return
	 */
	
	public String[] getFrames() {
		return frames;
	}
	public void setFrames(String[] frames) {
		this.frames = frames;
	}
	public int getNowPos() {
		return nowPos;
	}
	public void setNowPos(int nowPos) {
		this.nowPos = nowPos;
	}
	public int getSleepTime() {
		return sleepTime;
	}
	public void setSleepTime(int sleepTime) {
		this.sleepTime = sleepTime;
	}
	public boolean isIsloop() {
		return isloop;
	}
	public void setIsloop(boolean isloop) {
		this.isloop = isloop;
	}
	public KeepTask getKeepTask() {
		return keepTask;
	}
	public void setKeepTask(KeepTask keepTask) {
		this.keepTask = keepTask;
	} 
}
